<template>
  <div class="shop-relation-manager">
    <div class="relation-header">
      <h4>关联店铺管理</h4>
      <el-button type="primary" size="small" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加店铺关联
      </el-button>
    </div>

    <!-- 关联店铺列表 -->
    <div class="relation-list">
      <el-table
        :data="relationList"
        stripe
        border
        style="width: 100%"
        max-height="400"
      >
        <el-table-column prop="shopName" label="店铺名称" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="relationTypeName" label="关系类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getRelationTypeTagType(row.relationType)" size="small">
              {{ row.relationTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="ownershipRatio" label="所有权比例" width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.ownershipRatio && (typeof row.ownershipRatio === 'number' || !isNaN(parseFloat(row.ownershipRatio)))" class="ratio-text">
              {{ typeof row.ownershipRatio === 'number' ? row.ownershipRatio : parseFloat(row.ownershipRatio) }}%
            </span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="rentPrice" label="租金" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.rentPrice && typeof row.rentPrice === 'number'" class="price-text">¥{{ row.rentPrice.toFixed(2) }}</span>
            <span v-else-if="row.rentPrice && !isNaN(parseFloat(row.rentPrice))" class="price-text">¥{{ parseFloat(row.rentPrice).toFixed(2) }}</span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="租赁期间" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.leaseStartDate && row.leaseEndDate" class="date-range">
              {{ formatDate(row.leaseStartDate) }} - {{ formatDate(row.leaseEndDate) }}
            </span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="isPrimary" label="主要联系人" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              v-if="row.isPrimary === 1" 
              type="success" 
              size="small"
            >
              是
            </el-tag>
            <span v-else class="text-placeholder">否</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="statusName" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row, $index }">
            <el-button type="primary" size="small" @click="handleEdit(row, $index)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleRemove(row, $index)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑关联对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑店铺关联' : '添加店铺关联'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        size="default"
      >
        <el-form-item label="选择店铺" prop="shopId">
          <el-select
            v-model="formData.shopId"
            placeholder="请选择店铺"
            style="width: 100%"
            :disabled="isEdit"
            :loading="loading"
            filterable
            clearable
            no-data-text="暂无店铺数据"
            no-match-text="未找到匹配的店铺"
          >
            <el-option
              v-for="shop in availableShops"
              :key="shop.id"
              :label="shop.shopName"
              :value="shop.id"
            >
              <span style="float: left">{{ shop.shopName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ shop.shopTypeName }}</span>
            </el-option>
          </el-select>
          <div v-if="loading" class="loading-tip">
            <el-icon class="is-loading"><Loading /></el-icon>
            正在加载店铺列表...
          </div>
          <div v-else-if="availableShops.length === 0 && !loading" class="empty-tip">
            <el-icon><Warning /></el-icon>
            暂无可用店铺，请
            <el-button type="primary" link @click="retryLoadShopList">重新加载</el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="关系类型" prop="relationType">
          <el-radio-group v-model="formData.relationType">
            <el-radio :value="1">业主</el-radio>
            <el-radio :value="2">租户</el-radio>
            <el-radio :value="3">联合业主</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="所有权比例" prop="ownershipRatio">
          <el-input-number
            v-model="formData.ownershipRatio"
            :min="0"
            :max="100"
            :precision="2"
            :controls="false"
            style="width: 200px"
            placeholder="请输入所有权比例"
          />
          <span class="form-suffix">%</span>
        </el-form-item>
        
        <el-form-item label="租赁开始日期" prop="leaseStartDate">
          <el-date-picker
            v-model="formData.leaseStartDate"
            type="date"
            placeholder="请选择开始日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="租赁结束日期" prop="leaseEndDate">
          <el-date-picker
            v-model="formData.leaseEndDate"
            type="date"
            placeholder="请选择结束日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="租金价格" prop="rentPrice">
          <el-input-number
            v-model="formData.rentPrice"
            :min="0"
            :precision="2"
            :controls="false"
            style="width: 200px"
            placeholder="请输入租金价格"
          />
          <span class="form-suffix">元/月</span>
        </el-form-item>
        
        <el-form-item label="押金金额" prop="depositAmount">
          <el-input-number
            v-model="formData.depositAmount"
            :min="0"
            :precision="2"
            :controls="false"
            style="width: 200px"
            placeholder="请输入押金金额"
          />
          <span class="form-suffix">元</span>
        </el-form-item>
        
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input
            v-model="formData.contractNumber"
            placeholder="请输入合同编号"
            maxlength="50"
          />
        </el-form-item>
        
        <el-form-item label="是否主要联系人" prop="isPrimary">
          <el-radio-group v-model="formData.isPrimary">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '保存' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete, Loading, Warning } from '@element-plus/icons-vue'
import { shopApi } from '@/api/shop'
import { shopOwnerRelationApi } from '@/api/shop-owner-relation'
import type { ShopVO, ShopOwnerRelationVO } from '../types'

// Props
interface Props {
  modelValue: ShopOwnerRelationVO[]
  disabled?: boolean
  ownerId?: number
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  ownerId: 0
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: ShopOwnerRelationVO[]]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const showAddDialog = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const shopList = ref<ShopVO[]>([])
const loading = ref(false)

// 表单数据
const formData = reactive({
  shopId: null as number | null,
  relationType: 1,
  ownershipRatio: null as number | null,
  leaseStartDate: '',
  leaseEndDate: '',
  rentPrice: null as number | null,
  depositAmount: null as number | null,
  contractNumber: '',
  isPrimary: 0,
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  shopId: [
    { required: true, message: '请选择店铺', trigger: 'change' }
  ],
  relationType: [
    { required: true, message: '请选择关系类型', trigger: 'change' }
  ]
}

// 计算属性
const relationList = computed(() => props.modelValue || [])

const availableShops = computed(() => {
  const usedShopIds = relationList.value.map(rel => rel.shopId)
  return shopList.value.filter(shop => !usedShopIds.includes(shop.id))
})

// 监听器
watch(showAddDialog, (newVal) => {
  if (!newVal) {
    resetForm()
  }
})

// 方法
const loadShopList = async (showError = true) => {
  loading.value = true
  try {
    // 调用真实API获取店铺列表
    const response = await shopApi.getShopPage({
      current: 1,
      size: 100, // 获取店铺，限制在100以内
      status: 1 // 只获取启用的店铺
    })
    
    if (response && response.code === 200 && response.data) {
      shopList.value = response.data.records || []
      console.log('店铺列表加载成功:', shopList.value.length, '个店铺')
    } else {
      if (showError) {
        ElMessage.error(response?.message || '加载店铺列表失败')
      }
      shopList.value = []
    }
  } catch (error) {
    if (showError) {
      ElMessage.error('加载店铺列表失败，请检查网络连接')
    }
    console.error('加载店铺列表失败:', error)
    shopList.value = []
  } finally {
    loading.value = false
  }
}

// 重试加载店铺列表
const retryLoadShopList = () => {
  loadShopList(true)
}

const resetForm = () => {
  Object.assign(formData, {
    shopId: null,
    relationType: 1,
    ownershipRatio: null,
    leaseStartDate: '',
    leaseEndDate: '',
    rentPrice: null,
    depositAmount: null,
    contractNumber: '',
    isPrimary: 0,
    remark: ''
  })
  isEdit.value = false
  editIndex.value = -1
}

const handleEdit = (row: ShopOwnerRelationVO, index: number) => {
  isEdit.value = true
  editIndex.value = index
  
  // 确保数字字段的类型正确，遵循《Element Plus组件编码规范权威标准声明.md》
  Object.assign(formData, {
    shopId: row.shopId,
    relationType: row.relationType,
    ownershipRatio: row.ownershipRatio ? Number(row.ownershipRatio) : null,
    leaseStartDate: row.leaseStartDate || '',
    leaseEndDate: row.leaseEndDate || '',
    rentPrice: row.rentPrice ? Number(row.rentPrice) : null,
    depositAmount: row.depositAmount ? Number(row.depositAmount) : null,
    contractNumber: row.contractNumber || '',
    isPrimary: row.isPrimary,
    remark: row.remark || ''
  })
  
  showAddDialog.value = true
}

const handleRemove = async (row: ShopOwnerRelationVO, index: number) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除与店铺"${row.shopName}"的关联关系吗？`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    // 调用删除API
    const response = await shopOwnerRelationApi.deleteShopOwnerRelation(row.id)
    
    if (response && response.code === 200) {
      // 删除成功，更新本地数据
      const updatedList = [...relationList.value]
      updatedList.splice(index, 1)
      emit('update:modelValue', updatedList)
      
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 准备API调用数据
    const apiData = {
      shopId: formData.shopId!,
      ownerId: isEdit.value ? relationList.value[editIndex.value].ownerId : props.ownerId, // 编辑时使用现有ownerId，新增时使用props.ownerId
      relationType: formData.relationType,
      ownershipRatio: formData.ownershipRatio,
      leaseStartDate: formData.leaseStartDate || undefined,
      leaseEndDate: formData.leaseEndDate || undefined,
      rentPrice: formData.rentPrice,
      depositAmount: formData.depositAmount,
      contractNumber: formData.contractNumber || undefined,
      contractFile: undefined,
      isPrimary: formData.isPrimary,
      status: 1,
      remark: formData.remark || undefined
    }
    
    let relationData: ShopOwnerRelationVO
    
    if (isEdit.value) {
      // 编辑模式：调用更新API
      const relationId = relationList.value[editIndex.value].id
      const response = await shopOwnerRelationApi.updateShopOwnerRelation(relationId, apiData)
      
      if (response && response.code === 200) {
        // 更新成功，重新构建数据
        relationData = {
          ...relationList.value[editIndex.value],
          relationType: formData.relationType,
          relationTypeName: getRelationTypeName(formData.relationType),
          ownershipRatio: formData.ownershipRatio,
          leaseStartDate: formData.leaseStartDate,
          leaseEndDate: formData.leaseEndDate,
          rentPrice: formData.rentPrice,
          depositAmount: formData.depositAmount,
          contractNumber: formData.contractNumber,
          isPrimary: formData.isPrimary,
          remark: formData.remark,
          updateTime: new Date().toISOString()
        }
        
        const updatedList = [...relationList.value]
        updatedList[editIndex.value] = relationData
        emit('update:modelValue', updatedList)
        
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(response?.message || '编辑失败')
        return
      }
    } else {
      // 新增模式：调用创建API
      const response = await shopOwnerRelationApi.createShopOwnerRelation(apiData)
      
      if (response && response.code === 200) {
        // 创建成功，构建新数据
        const selectedShop = shopList.value.find(s => s.id === formData.shopId)
        relationData = {
          id: response.data || Date.now(),
          shopId: formData.shopId!,
          shopName: selectedShop?.shopName || '',
          ownerId: props.ownerId, // 使用props.ownerId
          ownerName: '',
          ownerPhone: '',
          ownerType: 1,
          ownerTypeName: '个人',
          companyName: '',
          relationType: formData.relationType,
          relationTypeName: getRelationTypeName(formData.relationType),
          ownershipRatio: formData.ownershipRatio,
          leaseStartDate: formData.leaseStartDate,
          leaseEndDate: formData.leaseEndDate,
          rentPrice: formData.rentPrice,
          depositAmount: formData.depositAmount,
          contractNumber: formData.contractNumber,
          contractFile: '',
          isPrimary: formData.isPrimary,
          status: 1,
          statusName: '启用',
          remark: formData.remark,
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString()
        }
        
        const updatedList = [...relationList.value, relationData]
        emit('update:modelValue', updatedList)
        
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(response?.message || '添加失败')
        return
      }
    }
    
    showAddDialog.value = false
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
      console.error('操作失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  showAddDialog.value = false
}

const getRelationTypeName = (relationType: number) => {
  switch (relationType) {
    case 1: return '业主'
    case 2: return '租户'
    case 3: return '联合业主'
    default: return '业主'
  }
}

const getRelationTypeTagType = (relationType: number) => {
  switch (relationType) {
    case 1: return 'success' // 业主
    case 2: return 'warning' // 租户
    case 3: return 'info'     // 联合业主
    default: return 'info'
  }
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadShopList()
})
</script>

<style scoped>
.shop-relation-manager {
  width: 100%;
}

.relation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.relation-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.relation-list {
  margin-top: 16px;
}

.dialog-footer {
  text-align: right;
}

.form-suffix {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.ratio-text {
  color: #409eff;
  font-weight: 500;
}

.price-text {
  color: #67c23a;
  font-weight: 600;
}

.date-range {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

/* 加载提示样式 */
.loading-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.loading-tip .el-icon {
  font-size: 14px;
}

/* 空状态提示样式 */
.empty-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #e6a23c;
  font-size: 12px;
}

.empty-tip .el-icon {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .relation-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .relation-list {
    overflow-x: auto;
  }
}
</style>
